package com.dn.lotte.ui.usercenter.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.dn.lotte.MainActivity;
import com.dn.lotte.R;
import com.dn.lotte.api.ServerApi;
import com.dn.lotte.api.UserCenterServerApi;
import com.dn.lotte.app.AppConstant;
import com.dn.lotte.app.GlobalApplication;
import com.dn.lotte.app.HttpURL;
import com.dn.lotte.bean.SafeQuesstionBean;
import com.dn.lotte.bean.SetSafequesBean;
import com.dn.lotte.bean.UserInfoBean;
import com.dn.lotte.bean.Vipbean;
import com.dn.lotte.ui.wonderful.activity.NewUserActivity;
import com.dn.lotte.utils.CommonUtils;
import com.dn.lotte.widget.ClearEditText;
import com.dn.lotte.widget.InputMethodRelativeLayout;
import com.easy.common.base.BaseActivity;
import com.easy.common.commonutils.SPUtils;
import com.easy.common.commonutils.StringUtils;
import com.easy.common.commonwidget.RippleView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.BitmapCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.popup.QMUIListPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.dn.lotte.R.id.codeBtn;
import static com.dn.lotte.R.id.codeImg;
import static com.dn.lotte.R.id.okBtn;

/**
 * ░░░░░░░░░░░░░░░░░░░░░░░░▄░░
 * ░░░░░░░░░▐█░░░░░░░░░░░▄▀▒▌░
 * ░░░░░░░░▐▀▒█░░░░░░░░▄▀▒▒▒▐
 * ░░░░░░░▐▄▀▒▒▀▀▀▀▄▄▄▀▒▒▒▒▒▐
 * ░░░░░▄▄▀▒░▒▒▒▒▒▒▒▒▒█▒▒▄█▒▐
 * ░░░▄▀▒▒▒░░░▒▒▒░░░▒▒▒▀██▀▒▌
 * ░░▐▒▒▒▄▄▒▒▒▒░░░▒▒▒▒▒▒▒▀▄▒▒
 * ░░▌░░▌█▀▒▒▒▒▒▄▀█▄▒▒▒▒▒▒▒█▒▐
 * ░▐░░░▒▒▒▒▒▒▒▒▌██▀▒▒░░░▒▒▒▀▄
 * ░▌░▒▄██▄▒▒▒▒▒▒▒▒▒░░░░░░▒▒▒▒
 * ▀▒▀▐▄█▄█▌▄░▀▒▒░░░░░░░░░░▒▒▒
 * 单身狗就这样默默地看着你，一句话也不说。
 * <p>
 * 登录
 *
 * @author DN
 * @data 2017/10/9
 **/
public class LoginActivity extends BaseActivity implements RippleView.OnRippleCompleteListener, InputMethodRelativeLayout.OnSizeChangedListenner {


    @Bind(R.id.de_frm_backgroud)
    FrameLayout mDeFrmBackgroud;
    @Bind(R.id.positionLiear)
    TextView mPositionLiear;
    @Bind(R.id.logoImg)
    ImageView mLogoImg;
    @Bind(R.id.codeValue)
    TextView mCodeValue;
    @Bind(R.id.view)
    View mView;
    @Bind(R.id.userName)
    ClearEditText mUserName;
    @Bind(R.id.usercenterPassword)
    TextView mUsercenterPassword;
    @Bind(R.id.pass)
    ClearEditText mPass;
    @Bind(R.id.VerifyPassword)
    TextView mVerifyPassword;
    @Bind(R.id.password_once)
    EditText mPasswordOnce;
    @Bind(okBtn)
    RippleView mOkBtn;
    @Bind(R.id.content)
    LinearLayout mContent;
    @Bind(R.id.scroll)
    ScrollView mScroll;
    @Bind(R.id.loginlayout)
    InputMethodRelativeLayout mLoginlayout;
    @Bind(codeImg)
    ImageView mCodeImg;
    @Bind(R.id.uncode)
    TextView uncode;
    @Bind(R.id.et_code)
    ClearEditText mCode;
    @Bind(R.id.rl_forget)
    RelativeLayout rlForget;
    @Bind(R.id.rl_newuser)
    RelativeLayout rlNewuser;
    @Bind(R.id.versionCode)
    TextView mVersionCode;
    @Bind(codeBtn)
    RippleView mCodeBtn;

    private String mUserNameStr;
    private String mPassStr;
    private AlertDialog dialog;
    private ClearEditText et_username;
    private RippleView rl_wenti;
    private TextView rv_wenti;
    private ClearEditText et_answer;
    private List<SafeQuesstionBean.TableBean> mlistsafe;
    private QMUIListPopup mListPopup;
    private ClearEditText et_qrnewpsw;
    private ClearEditText et_newpsw;

    @Override
    public int getLayoutId() {
        return R.layout.act_login;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        //获取验证码
        getCode();
        mOkBtn.setOnRippleCompleteListener(this);
        mLoginlayout.setOnSizeChangedListenner(this);
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                Animation animation = AnimationUtils.loadAnimation(LoginActivity.this, R.anim.translate_anim);
//                mIvImgBackgroud.startAnimation(animation);
//            }
//        }, 200);
        mVersionCode.setText("当前版本：" + CommonUtils.getVersion(mContext));
        mCodeBtn.setOnRippleCompleteListener(this);
        if (!StringUtils.isEmpty(SPUtils.getSharedStringData(mContext, AppConstant.LOGINPASS)))
            mPass.setText(SPUtils.getSharedStringData(mContext, AppConstant.LOGINPASS));
        //记录上次登录的手机号 对用户有好一点
        if (!StringUtils.isEmpty(SPUtils.getSharedStringData(mContext, AppConstant.LOGINPHONE)))
            mUserName.setText(SPUtils.getSharedStringData(mContext, AppConstant.LOGINPHONE));

    }

    private void getCode() {
        OkGo.<Bitmap>get(HttpURL.Base_Url + HttpURL.code)
                .execute(new BitmapCallback() {
                    @Override
                    public void onSuccess(Response<Bitmap> response) {
                        if (mCodeImg != null) mCodeImg.setImageBitmap(response.body());
//                        showShortToast("ssss");
                    }
                });
    }

    @Override
    public void onSizeChange(boolean paramBoolean, int w, int h) {
        if (paramBoolean) {// 键盘弹出时
//            mPositionLiear.setVisibility(View.GONE);
            ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(mContent, "translationY", 0.0f, -10);
            mAnimatorTranslateY.setDuration(300);
            mAnimatorTranslateY.setInterpolator(new LinearInterpolator());
            mAnimatorTranslateY.start();
            mPositionLiear.setVisibility(View.GONE);
            zoomIn(mLogoImg, 0.6f, 10);
        } else { // 键盘隐藏时
//            mPositionLiear.setVisibility(View.VISIBLE);
            ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(mContent, "translationY", mContent.getTranslationY(), 0);
            mAnimatorTranslateY.setDuration(300);
            mAnimatorTranslateY.setInterpolator(new LinearInterpolator());
            mAnimatorTranslateY.start();
            //键盘收回后，logo恢复原来大小，位置同样回到初始位置
            zoomOut(mLogoImg, 0.6f);
            mPositionLiear.setVisibility(View.VISIBLE);

        }
    }

    /**
     * 缩小
     *
     * @param view
     */
    public static void zoomIn(final View view, float scale, float dist) {
        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();
        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", 1.0f, scale);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", 1.0f, scale);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", 0.0f, -dist);

        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX);
        mAnimatorSet.play(mAnimatorScaleX).with(mAnimatorScaleY);
        mAnimatorSet.setDuration(300);
        mAnimatorSet.start();
    }

    /**
     * f放大
     *
     * @param view
     */
    public static void zoomOut(final View view, float scale) {
        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();

        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", scale, 1.0f);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", scale, 1.0f);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", view.getTranslationY(), 0);

        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX);
        mAnimatorSet.play(mAnimatorScaleX).with(mAnimatorScaleY);
        mAnimatorSet.setDuration(300);
        mAnimatorSet.start();
    }

    @Override
    public void onComplete(RippleView rippleView) {
        switch (rippleView.getId()) {
            case R.id.okBtn:

                mUserNameStr = mUserName.getText().toString().trim();
                mPassStr = mPass.getText().toString().trim();
//                showEditTextDialog();
                String mCodeStr = mCode.getText().toString().trim();
                if (!StringUtils.isEmpty(mUserNameStr)) {
                    if (!StringUtils.isEmpty(mPassStr)) {
                        if (!StringUtils.isEmpty(mCodeStr)) {
                            HttpParams params = new HttpParams();
                            params.put("Name", mUserNameStr);
                            params.put("Pass", mPassStr);
                            params.put("Code", mCodeStr);
                            doLogin(params);
                        } else
                            showShortToast("请输入验证码");
                    } else {
                        showShortToast("请输入密码");
                    }
                } else
                    showShortToast("请输入用户名");
                break;
            case R.id.rl_wenti:
                GetsafeQuesstion(rippleView);
                break;
            case R.id.codeBtn:
                getCode();
                break;
        }
    }


    private void showEditTextDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(mContext);
        builder.setTitle("登录异常验证")
                .setPlaceholder("输入真实姓名")
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        String text = builder.getEditText().getText().toString();
                        Log.i("DNLOG", text);
                        if (text != null && text.length() > 0) {
                            HttpParams params = new HttpParams();
                            params.put("Name", mUserNameStr);
                            params.put("Pass", mPassStr);
                            params.put("tname", text);
                            doLogin2(params);
                            dialog.dismiss();
                        } else {
                            Toast.makeText(mContext, "请填入您的真实姓名", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .show();
    }

    private void doLogin2(HttpParams params) {

        ServerApi.getLogoinData2(params)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserInfoBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull UserInfoBean userInfoBean) {
                        if ("1".equals(userInfoBean.getResult())) {
                            getVipInfoData();
                            SPUtils.setSharedStringData(mContext, AppConstant.BANK, userInfoBean.getTable().get(0).getUserbank());
                            SPUtils.setSharedStringData(mContext, AppConstant.LOGINPHONE, mUserNameStr);
                            SPUtils.setSharedStringData(mContext, AppConstant.LOGINPASS, mPassStr);
                        } else if ("2".equals(userInfoBean.getResult())) {
                            stopProgressDialog();
                            showShortToast(userInfoBean.getReturnval());
                            showEditTextDialog();
                        } else {
                            stopProgressDialog();
                            showShortToast(userInfoBean.getReturnval());
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();
                        showShortToast("登录失败，请检查您的网络！");
                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }

    private void doLogin(HttpParams params) {

        ServerApi.getLogoinData(params)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserInfoBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull UserInfoBean userInfoBean) {
                        if ("1".equals(userInfoBean.getResult())) {
                            getVipInfoData();
                            SPUtils.setSharedStringData(mContext, AppConstant.LOGINPHONE, mUserNameStr);
                            SPUtils.setSharedStringData(mContext, AppConstant.LOGINPASS, mPassStr);
                            SPUtils.setSharedStringData(mContext, AppConstant.BANK, userInfoBean.getTable().get(0).getUserbank());
                        } else if ("2".equals(userInfoBean.getResult())) {
                            stopProgressDialog();
                            showShortToast(userInfoBean.getReturnval());
                            showEditTextDialog();
                        } else {
                            stopProgressDialog();
                            showShortToast(userInfoBean.getReturnval());
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();
                        showShortToast("登录失败，请检查您的网络！");
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }
/*
    //弹出绑定真是姓名对话框，强制绑定
    private void showPopTrueName() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(mContext);
        builder.setTitle("真实姓名没有绑定，请绑定!")
                .setPlaceholder("输入真实姓名")
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        String text = builder.getEditText().getText().toString();
                        Log.i("DNLOG", text);
                        if (text != null && text.length() > 0) {
                            HttpParams params = new HttpParams();
                            params.put("name", text);
                            realNameUrl(params);
                            dialog.dismiss();
                        } else {
                            Toast.makeText(mContext, "请填入您的真实姓名", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .show();
    }*/
/*
    private void realNameUrl(HttpParams params) {
        UserCenterServerApi.setRealname(params)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        stopProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SetSafequesBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onNext(@NonNull SetSafequesBean setSafequesBean) {
                        stopProgressDialog();
                        showShortToast(setSafequesBean.getReturnval());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();
                    }
                });

    }*/

    private void getVipInfoData() {
        ServerApi.getVipInfoData()
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
//                startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Vipbean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Vipbean vipbean) {
                        String point = vipbean.getTable().get(0).getPoint();
                        Log.i("DDD", point);
                        float i;
                        if (!StringUtils.isEmpty(point)) {
                            i = (float) Double.parseDouble(point.substring(0, point.length() - 1));
                        } else {
                            i = 0;
                        }
                        SPUtils.setSharedStringData(mContext, "POINT", i + "");
                        GlobalApplication.getInstance().setUserModel(vipbean);
                        GlobalApplication.getInstance().setLogin(true);
                        startActivity(MainActivity.class);
                        finish();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();
                    }
                });
    }


    @OnClick({R.id.rl_forget, R.id.rl_newuser})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_forget://忘记密码
                showDialogforget();
                break;
            case R.id.rl_newuser://新用户注册
                startActivity(NewUserActivity.class);
                break;
        }
    }

    private void showDialogforget() {
        dialog = new AlertDialog.Builder(this)
                .setView(R.layout.forgetpassword)
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.d("tag", "setPositiveButton");
                        try {
                            Field field = dialog.getClass()
                                    .getSuperclass().getSuperclass().getDeclaredField(
                                            "mShowing");
                            field.setAccessible(true);
                            //   将mShowing变量设为false，表示对话框已关闭
                            field.set(dialog, false);
                            dialog.dismiss();

                        } catch (Exception e) {

                        }
                    }
                })
                .setNegativeButton("cancle", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        try {
                            Field field = dialog.getClass()
                                    .getSuperclass().getSuperclass().getDeclaredField(
                                            "mShowing");
                            field.setAccessible(true);
                            //   将mShowing变量设为false，表示对话框已关闭
                            field.set(dialog, true);
                            dialog.dismiss();

                        } catch (Exception e) {

                        }
                    }
                })
                .setCancelable(false)
                .create();
        dialog.show();
        et_username = (ClearEditText) dialog.findViewById(R.id.et_username);
        Button mNegativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
        Button mPOstiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        mNegativeButton.setText("下一步");
        mPOstiveButton.setText("取消");
        mNegativeButton.setTextColor(Color.parseColor("#0079ff"));
        mPOstiveButton.setTextColor(Color.parseColor("#a3a3a3"));
        mPOstiveButton.setTextAppearance(this, R.style.Mycustomtab);
        mPOstiveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        mNegativeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!StringUtils.isEmpty(et_username.getText().toString())) {
                    HttpParams httpParams = new HttpParams();
                    httpParams.put("name", et_username.getText().toString());
                    ServerApi.getverifynumber(httpParams)
                            .doOnSubscribe(new Consumer<Disposable>() {
                                @Override
                                public void accept(@NonNull Disposable disposable) throws Exception {
                                    startProgressDialog();
                                }
                            })
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<SetSafequesBean>() {
                                @Override
                                public void onSubscribe(@NonNull Disposable d) {
                                    stopProgressDialog();
                                }

                                @Override
                                public void onNext(@NonNull SetSafequesBean setSafequesBean) {
                                    stopProgressDialog();
                                    if (setSafequesBean.getResult().equals("1")) {
                                        dialog.dismiss();
                                        showDialogforgetanswor(et_username.getText().toString());
                                    }
                                    showShortToast(setSafequesBean.getReturnval());
                                }

                                @Override
                                public void onError(@NonNull Throwable e) {
                                    stopProgressDialog();

                                }

                                @Override
                                public void onComplete() {
                                    stopProgressDialog();

                                }
                            });
                } else {
                    showShortToast("请输入用户名");
                }
            }
        });
    }

    private void showDialogforgetanswor(final String stringname) {
        dialog = new AlertDialog.Builder(this)
                .setView(R.layout.forgetpswanswnor)
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.d("tag", "setPositiveButton");
                        try {
                            Field field = dialog.getClass()
                                    .getSuperclass().getSuperclass().getDeclaredField(
                                            "mShowing");
                            field.setAccessible(true);
                            //   将mShowing变量设为false，表示对话框已关闭
                            field.set(dialog, false);
                            dialog.dismiss();

                        } catch (Exception e) {

                        }
                    }
                })
                .setNegativeButton("cancle", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        try {
                            Field field = dialog.getClass()
                                    .getSuperclass().getSuperclass().getDeclaredField(
                                            "mShowing");
                            field.setAccessible(true);
                            //   将mShowing变量设为false，表示对话框已关闭
                            field.set(dialog, true);
                            dialog.dismiss();

                        } catch (Exception e) {

                        }
                    }
                })
                .setCancelable(false)
                .create();
        dialog.show();
        et_answer = (ClearEditText) dialog.findViewById(R.id.et_answer);
        rl_wenti = (RippleView) dialog.findViewById(R.id.rl_wenti);
        rv_wenti = (TextView) dialog.findViewById(R.id.rv_wenti);
        Button mNegativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
        Button mPOstiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        mNegativeButton.setText("确定");
        mPOstiveButton.setText("取消");
        mNegativeButton.setTextColor(Color.parseColor("#0079ff"));
        mPOstiveButton.setTextColor(Color.parseColor("#a3a3a3"));
        mPOstiveButton.setTextAppearance(this, R.style.Mycustomtab);
        mPOstiveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        mNegativeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = rv_wenti.getText().toString();

                if (!rv_wenti.getText().toString().equals("请选择问题")) {
                    if (!StringUtils.isEmpty(et_answer.getText().toString())) {
                        HttpParams params = new HttpParams();
                        params.put("name", stringname);
                        params.put("question", rv_wenti.getText().toString());
                        params.put("answer", et_answer.getText().toString());
                        ServerApi.getverifypswanswnor(params)
                                .doOnSubscribe(new Consumer<Disposable>() {
                                    @Override
                                    public void accept(@NonNull Disposable disposable) throws Exception {
                                        startProgressDialog();
                                    }
                                })
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Observer<SetSafequesBean>() {
                                    @Override
                                    public void onSubscribe(@NonNull Disposable d) {
                                        stopProgressDialog();
                                    }

                                    @Override
                                    public void onNext(@NonNull SetSafequesBean setSafequesBean) {
                                        stopProgressDialog();
                                        if (setSafequesBean.getResult().equals("1")) {
                                            dialog.dismiss();
                                            showDialogxgpsw(stringname, rv_wenti.getText().toString(), et_answer.getText().toString());
                                        }
                                        showShortToast(setSafequesBean.getReturnval());

                                    }

                                    @Override
                                    public void onError(@NonNull Throwable e) {
                                        stopProgressDialog();

                                    }

                                    @Override
                                    public void onComplete() {
                                        stopProgressDialog();

                                    }
                                });
                    } else {
                        showShortToast("请输入问题答案");
                    }
                } else {
                    showShortToast("请选择问题");
                }
            }
        });
        rl_wenti.setOnRippleCompleteListener(this);
    }

    //修改密码
    private void showDialogxgpsw(final String stringname, final String question, final String answnor) {
        dialog = new AlertDialog.Builder(this)
                .setView(R.layout.xgpsw)
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.d("tag", "setPositiveButton");
                        try {
                            Field field = dialog.getClass()
                                    .getSuperclass().getSuperclass().getDeclaredField(
                                            "mShowing");
                            field.setAccessible(true);
                            //   将mShowing变量设为false，表示对话框已关闭
                            field.set(dialog, false);
                            dialog.dismiss();

                        } catch (Exception e) {

                        }
                    }
                })
                .setNegativeButton("cancle", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        try {
                            Field field = dialog.getClass()
                                    .getSuperclass().getSuperclass().getDeclaredField(
                                            "mShowing");
                            field.setAccessible(true);
                            //   将mShowing变量设为false，表示对话框已关闭
                            field.set(dialog, true);
                            dialog.dismiss();

                        } catch (Exception e) {

                        }
                    }
                })
                .setCancelable(false)
                .create();
        dialog.show();
        et_newpsw = (ClearEditText) dialog.findViewById(R.id.et_newpsw);
        et_qrnewpsw = (ClearEditText) dialog.findViewById(R.id.et_qrnewpsw);

        Button mNegativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
        Button mPOstiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        mNegativeButton.setText("确定");
        mPOstiveButton.setText("取消");
        mNegativeButton.setTextColor(Color.parseColor("#0079ff"));
        mPOstiveButton.setTextColor(Color.parseColor("#a3a3a3"));
        mPOstiveButton.setTextAppearance(this, R.style.Mycustomtab);
        mPOstiveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        mNegativeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!StringUtils.isEmpty(et_newpsw.getText().toString()) || !StringUtils.isEmpty(et_qrnewpsw.getText().toString())) {
                    if (et_qrnewpsw.getText().toString().equals(et_newpsw.getText().toString())) {
                        HttpParams params = new HttpParams();
                        params.put("name", stringname);
                        params.put("question", question);
                        params.put("answer", answnor);
                        params.put("pass", et_qrnewpsw.getText().toString());
                        ServerApi.setpsw(params)
                                .doOnSubscribe(new Consumer<Disposable>() {
                                    @Override
                                    public void accept(@NonNull Disposable disposable) throws Exception {
                                        startProgressDialog();
                                    }
                                })
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Observer<SetSafequesBean>() {
                                    @Override
                                    public void onSubscribe(@NonNull Disposable d) {
                                        stopProgressDialog();
                                    }

                                    @Override
                                    public void onNext(@NonNull SetSafequesBean setSafequesBean) {
                                        stopProgressDialog();
                                        if (setSafequesBean.getResult().equals("1")) {
                                            dialog.dismiss();
                                        }
                                        showShortToast(setSafequesBean.getReturnval());

                                    }

                                    @Override
                                    public void onError(@NonNull Throwable e) {
                                        stopProgressDialog();

                                    }

                                    @Override
                                    public void onComplete() {
                                        stopProgressDialog();

                                    }
                                });
                    } else {
                        showShortToast("俩次密码不一致");
                    }
                } else {
                    showShortToast("密码不能为空");
                }
            }
        });
    }

    //请求安全问题
    private void GetsafeQuesstion(final RippleView rippleView) {
        UserCenterServerApi.getSafeQuesstion()
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {

                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SafeQuesstionBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull SafeQuesstionBean safeQuesstionBean) {
                        if (safeQuesstionBean.getResult().equals("1")) {
                            mlistsafe = safeQuesstionBean.getTable();
                            initListPopupIfNeed(mlistsafe);
                            mListPopup.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_LEFT);
                            mListPopup.setPreferredDirection(QMUIPopup.DIRECTION_BOTTOM);
                            mListPopup.show(rippleView);
                        } else {
                            showShortToast(safeQuesstionBean.getReturnval());
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initListPopupIfNeed(List<SafeQuesstionBean.TableBean> mlistsafe) {
        if (mListPopup == null) {
            final List<String> data = new ArrayList<>();
            for (SafeQuesstionBean.TableBean tableBean : mlistsafe) {
                data.add(tableBean.getTitle());
            }

            ArrayAdapter adapter = new ArrayAdapter<>(mContext, R.layout.simple_list_item, data);
            mListPopup = new QMUIListPopup(mContext, QMUIPopup.DIRECTION_NONE, adapter);
            mListPopup.create(QMUIDisplayHelper.dp2px(mContext, 180), QMUIDisplayHelper.dp2px(mContext, 220), new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    rv_wenti.setText(data.get(i));
                    mListPopup.dismiss();
                }
            });
            mListPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                }
            });
        }
    }
}
